<template>
	<view class="cart-page">
		<!-- 底部结算区域style="bottom: 241rpx;" -->
		<view class="cart_b" >
			<view class="cart-footer">
				<view class="cart-summary ">
					<view class="flex_align_conter" @tap="openPopup">
						<image src="@/static/images/icons/shoppingBag.svg" class="bag-icon" />
						<view class="" style="margin-top: 10rpx;">
							<text>已选 <text style="color: #0EB275;margin: 0 8rpx;"> {{ selectedSummary.totalNum }}</text>
								件</text>
						</view>
					</view>
					<view class="flex_align_conter" style="padding-top: 18rpx;">
						<text class="price">合计 ¥ </text><text style="font-size: 44rpx;margin-left: 4rpx;">
							{{ selectedSummary.totalPrice.toFixed(2) }}</text>
					</view>
				</view>
				<view class="checkout-btn flex_center" @click="closeAccount"> 去结算</view>
			</view>
		</view>

		<!-- 套餐弹窗 -->
		<uni-popup ref="popup" type="bottom" class="">
			<view class="popup-container">
				<view class="popup-header">
					<text>已选商品</text>
					<view class="clear-btn flex_align_conter">
						<uni-icons color="#848484" type="trash" size="16"></uni-icons>
						<view class="" style="margin-right: 40rpx;" @tap="clearCart">
							清空购物车
						</view>
						<uni-icons @click="closePopup" color="#323232" type="closeempty" size="16"></uni-icons>
					</view>
				</view>

				<!-- 
				<scroll-view scroll-y style="max-height: 400rpx">
						<view class="meal-info">
							<view class="meal-title">{{ item.name }}</view>
							<view class="meal-detail">主料：{{ item.ingredients }}</view>
							<view class="meal-price">¥{{ item.price }}</view>
							<view class="counter">
								<button class="btn minus" @tap="decrease(index)">-</button>
								<text class="count">{{ item.count }}</text>
								<button class="btn plus" @tap="increase(index)">+</button>
							</view>
						</view>
					</view>
				</scroll-view> -->
				<scroll-view scroll-y style="max-height: 900rpx;">

					<view class="cart_box" v-if="cartList.length>0">
						<view class="" v-for="item in cartList">
							<view class="" v-if="
							(item.dictDataList.meals1&&item.dictDataList.meals1.comboList&&item.dictDataList.meals1.comboList.length > 0 )||  
							(item.dictDataList.meals1&&item.dictDataList.meals1.dishList&&item.dictDataList.meals1.dishList.length > 0) ||  
							(item.dictDataList.meals2&&item.dictDataList.meals2.comboList&&item.dictDataList.meals2.comboList.length > 0) ||  
							(item.dictDataList.meals2&&item.dictDataList.meals2.dishList&&item.dictDataList.meals2.dishList.length > 0) ">
								<view class="cart_date" style="display: flex;justify-content: space-between
" v-if="item.fullDate">
									<view class="">
										{{item.fullDate.replace(/-/g, "/")}}
									</view>
									<view class="" style="margin-top: -5rpx;background-color: #0EB275;color: white;padding: 5rpx 15rpx;font-size: 12px;border-radius: 60rpx 60rpx 0 60rpx;margin-left: 15rpx;">
										{{getDayOfWeek(item.fullDate)}}
									</view>
								</view>
								<view v-else class="cart_date" style="display: flex;justify-content: space-between">
									<view class="">
										{{date}}
									</view>
									<view class="" style="margin-top: -5rpx;background-color: #0EB275;color: white;padding: 5rpx 15rpx;font-size: 12px;border-radius: 60rpx 60rpx 0 60rpx;margin-left: 15rpx;">
										{{getDayOfWeek(item.fullDate)}}
									</view>
								</view>
								<view class=""
									v-if="item.dictDataList.meals1&&(item.dictDataList.meals1.comboList.length > 0 || item.dictDataList.meals1.dishList.length > 0 )">
									<view class="icons flex_align_conter">
										<image style="width: 24rpx;height: 24rpx;"
											src="@/static/images/icons/meal_1.svg" mode="">
										</image>
										<view class="" style="margin: 0 8rpx;">
											餐品
										</view>
										<view class="title">
											早餐
										</view>
									</view>
									<setMealReservation v-for="d in item.dictDataList.meals1.comboList" :item="d"
										@updateNum="handleUpdateNum">
									</setMealReservation>
									<setMealReservation v-for="d in item.dictDataList.meals1.dishList" :item="d"
										@updateNum="handleUpdateNum">
									</setMealReservation>
								</view>
								<view class=""
									v-if="item.dictDataList.meals2.comboList.length > 0 ||item.dictDataList.meals2.dishList.length > 0 ">
									<view class="icons flex_align_conter">
										<image style="width: 24rpx;height: 24rpx;"
											src="@/static/images/icons/meal_1.svg" mode="">
										</image>
										<view class="" style="margin: 0 8rpx;">
											餐品
										</view>
										<view class="title">
											午餐
										</view>
									</view>
									<setMealReservation v-for="d in item.dictDataList.meals2.comboList" :item="d"
										@updateNum="handleUpdateNum">
									</setMealReservation>
									<setMealReservation v-for="d in item.dictDataList.meals2.dishList" :item="d"
										@updateNum="handleUpdateNum">
									</setMealReservation>
								</view>

							</view>
						</view>
					</view>
					<!-- <view class="">
						<u-empty mode="data" icon="http://cdn.uviewui.com/uview/empty/data.png">
						</u-empty>
					</view> -->
				</scroll-view>

			</view>
			<view class="cart_b_interior">
				<view class="cart-footer">
					<view class="cart-summary ">
						<view class="flex_align_conter" @tap="closePopup">
							<image src="@/static/images/icons/shoppingBag.svg" class="bag-icon" />
							<view class="" style="margin-top: 10rpx;">
								<text>已选 <text style="color: #0EB275;margin: 0 8rpx;">
										{{ selectedSummary.totalNum }}</text>
									件</text>
							</view>
						</view>
						<view class="flex_align_conter" style="padding-top: 18rpx;">
							<text class="price">合计 ¥ </text><text style="font-size: 44rpx;margin-left: 4rpx;">
								{{ selectedSummary.totalPrice.toFixed(2) }}</text>
						</view>
					</view>
					<view class="checkout-btn flex_center" @click="closeAccount"> 去结算</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'
	import setMealReservation from '@/components/common/setMealReservation.vue'
	export default {
		props: {
			cartList: {
				type: Array,
				default: () => []
			},
			orderId: {
				type: String,
				default: ''
			},
			date: {
				type: String,
				default: ''
			},
			phone:{
				type: String,
				default:""
			},
			num:{
				type: String,
				default:""
			},
			weekNewType:{
				typeof:Number,
				default:0
			},
			siteName:{
				typeof:String,
				default:""
			},
			siteId:{
				typeof:String,
				default:0
			}
		},
		components: {
			setMealReservation
		},
		data() {
			return {
				morningPackageList: [],
			}
		},
		options: {
			styleIsolation: 'shared'
		},
		watch: {
			// 监听父组件传入数据变化
			cartList: {
				handler(newVal) {
					// this.localCartList = JSON.parse(JSON.stringify(newVal)) // 深拷贝
					console.log(this.cartList)
				},
				immediate: true,
				deep: true
			}
		},
		computed: {
			...mapState({
				shoppingBagData: state => state.user.shoppingBagData
			}),
			selectedSummary() {
				
				let totalNum = 0
				console.log(this.cartList);
				let totalPrice = 0
				this.cartList.forEach(day => {
					const meals = ['meals1', 'meals2','meals3']
					const lists = ['comboList', 'dishList']

					meals.forEach(mealKey => {
						lists.forEach(listKey => {
							const list = day.dictDataList?.[mealKey]?.[listKey] || []
							list.forEach(item => {
								const saleNum = Number(item.saleNum)
								const price = Number(item.price)
								// console.log(price);
								if (saleNum > 0) {
									totalNum += saleNum
									totalPrice += saleNum * price
								}
							})
						})
					})
				})

				return {
					totalNum,
					totalPrice
				}
			}
		},
		created() {
		},
		mounted() {
			// this.$refs.popup.open()

		},
		methods: {
			getDayOfWeek(dateStr) {
			  const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
			  const date = new Date(dateStr);
			  const dayIndex = date.getDay(); // 0 是星期日，1 是星期一，...，6 是星期六
			  return days[dayIndex];
			},
			getNextWeekSameDay(dateStr) {
			    // 1. 解析输入日期
			    const date = new Date(dateStr);
			    
			    // 2. 获取星期几（0=周日, 1=周一, ..., 6=周六）
			    const dayOfWeek = date.getDay();
			    const days = ["周日", "周一", "周二", "周三", "周四", "周五", "周六"];
			    console.log(`${dateStr} 是 ${days[dayOfWeek]}`);
			
			    // 3. 计算下一周同一天的日期（+7 天）
			    const nextWeekSameDay = new Date(date);
			    nextWeekSameDay.setDate(date.getDate() + 7);
			    const formattedNextDate = nextWeekSameDay.toISOString().split('T')[0];
			
			    console.log(`下一周 ${days[dayOfWeek]} 的日期是 ${formattedNextDate}`);
			    return formattedNextDate;
			},
			closeAccount() {
				if (this.selectedSummary.totalNum == 0) {
					this.$modal.msg('请选择要预定的餐')
					return false;
				}
				uni.navigateTo({
						url:`/subpackages/user/pages/placeorder/placeorder?orderId=${this.orderId}&date=${this.date}&phone=${this.phone}&num=${this.num}&weekNewType=${this.weekNewType}&siteName=${this.siteName}&siteId=${this.siteId}`})
			},
			updateNumById(contentData, targetId, newNum = 0, clearAll = false) {
				return contentData.map(day => {
					const newDay = JSON.parse(JSON.stringify(day))
					const meals = ['meals1', 'meals2']
					const lists = ['comboList', 'dishList']

					meals.forEach(mealKey => {
						lists.forEach(listKey => {
							const list = newDay.dictDataList?.[mealKey]?.[listKey]
							if (Array.isArray(list)) {
								list.forEach(item => {
									// 如果是清空所有，或者当前 item.id 匹配目标 id，就设置 num
									if (clearAll || item.lzy_id === targetId) {
										item.saleNum = newNum
									}
								})
							}
						})
					})

					return newDay
				})
			},
			handleUpdateNum(item, newNum) {
				// console.log(this.shoppingBagData);
				// return
				const newtData = this.updateNumById(this.shoppingBagData, item.lzy_id, newNum)
				this.$store.commit('SET_SHOPPINGBAGDATA', newtData)
				this.$emit('undateData')

			},
			openPopup() {
				this.$refs.popup.open()
			},
			closePopup() {
				this.$refs.popup.close()
			},
			clearCart() {
				const newtData = this.updateNumById(this.shoppingBagData, null, 0, true)
				this.$store.commit('SET_SHOPPINGBAGDATA', newtData)
				this.$emit('undateData')
			},
			increase(index) {
				this.localCartList[index].count++
				this.emitUpdate()
			},
			decrease(index) {
				if (this.localCartList[index].count > 0) {
					this.localCartList[index].count--
					this.emitUpdate()
				}
			},
			emitUpdate() {
				// 派发更新事件
				this.$emit('updateCart', this.localCartList)
			}
		}
	}
</script>


<style scoped lang="scss">
	.cart_b {
		padding: 0 20rpx;
		width: 100%;
		height: 120rpx;
		position: fixed;
		bottom: 180rpx;
		// z-index: 999999999;
		left: 0;
		right: 0;
	}

	.cart_b_interior {
		background: #fff;
		padding: 0 20rpx 40rpx;
	}

	.cart-footer {
		width: 100%;
		height: 120rpx;
		background: #fff;
		border-top: 1px solid #eee;
		display: flex;
		justify-content: space-between;
		align-items: center;
		box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.05);
		border-radius: 80rpx;
		overflow: hidden;
		color: #fff;
	}

	.cart-summary {
		display: flex;
		justify-content: space-around;
		// padding: 0 40rpx 0 70rpx;
		flex: 1;
		height: 100%;
		background: #010E09;
		// align-items: end;
	}

	.bag-icon {

		width: 80rpx;
		height: 100rpx;
	}

	.price {
		font-weight: 500;
		margin-left: 16rpx;
	}

	.checkout-btn {
		width: 220rpx;
		height: 100%;

		background: #0EB275;
		color: white;
		font-size: 36rpx;
	}

	.popup-container {
		background: #fff;
		border-top-left-radius: 20rpx;
		border-top-right-radius: 20rpx;
		padding: 30rpx 40rpx;


		.cart_date {
			margin-bottom: 20rpx;
		}

		.icons {
			margin-bottom: 12rpx;

			.title {

				display: inline-block;
				border-radius: 8rpx;
				/* 主色 */
				background: #E6F7F1;
				font-size: 20rpx;
				color: #0EB275;
				padding: 4rpx 10rpx;
			}
		}
	}

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-bottom: 20rpx;
		border-bottom: 2rpx solid #f3f3f3;
	}

	.clear-btn {
		color: #999;
		font-size: 24rpx;
	}

	.meal-card {
		display: flex;
		margin-bottom: 24rpx;
	}

	.meal-image {
		width: 120rpx;
		height: 120rpx;
		border-radius: 12rpx;
		margin-right: 20rpx;
	}

	.meal-info {
		flex: 1;
		position: relative;
	}

	.meal-title {
		font-weight: bold;
		font-size: 30rpx;
	}

	.meal-detail {
		color: #999;
		font-size: 24rpx;
		margin: 8rpx 0;
	}

	.meal-price {
		color: #f40;
		font-weight: bold;
	}

	.counter {
		position: absolute;
		right: 0;
		bottom: 0;
		display: flex;
		align-items: center;
	}

	.btn {
		background: #00c777;
		color: #fff;
		border: none;
		width: 48rpx;
		height: 48rpx;
		border-radius: 50%;
		text-align: center;
		line-height: 48rpx;
	}

	.count {
		margin: 0 12rpx;
	}

	.cart_box {
		margin-top: 20rpx;

		::v-deep .card_b {
			padding: 24rpx 0;
			/* 必要时用 !important 提高优先级 */
			/* 其他覆盖样式 */
		}
	}

	// .parent-card-b {
	// 	padding: 24rpx 0 !important;
	// 	/* 必要时用 !important 提高优先级 */
	// 	/* 其他覆盖样式 */
	// }
</style>